package es.ise.core.controllers;

import java.lang.reflect.Field;
import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import es.ise.circulo.mappers.ClienteMapper;
import es.ise.circulo.model.Cliente;
import es.ise.circulo.model.example.ClienteExample;
import es.ise.core.model.Column;
import es.ise.core.stereotypes.AjaxController;

/**
 * Controlador que ejecuta diferentes tests
 * 
 * @author Paco
 */
@Controller
@RequestMapping("/test")
public class TestController
{
	@RequestMapping("/theme")
	public ModelAndView test()
	{
		ModelAndView mav = new ModelAndView("test/theme");
		return mav;
	}
	
	@RequestMapping("/jqgrid")
	public ModelAndView jqgrid()
	{
		return new ModelAndView("test/jqgrid");
	}
	
	@AjaxController
	@RequestMapping("/test/jqgrid/data")
	public static class JqGridAjaxController
	{
		@Autowired
		private ClienteMapper clienteMapper;
		
		@RequestMapping("/example")
		public ModelAndView jqgridData(
				@RequestParam(required=false) String[] filter,
				@RequestParam(value="rows", required=false, defaultValue="10") int filas,
				@RequestParam(value="page", required=false, defaultValue="1") int pagina,
				@RequestParam(value="sidx", required=false, defaultValue="") String ordenacion,
				@RequestParam(value="sord", required=false, defaultValue="asc") String tipoOrdenacion
		) throws SecurityException, NoSuchFieldException
		{
			ModelAndView mav = new ModelAndView("json");
			ClienteExample example = new ClienteExample();
			if(!ordenacion.equals(""))
			{
				Field field = Cliente.class.getDeclaredField(ordenacion);
				Column column = field.getAnnotation(Column.class);
				example.setOrderByClause(String.format("%s %s", column.value(), tipoOrdenacion));
			}
			int totalfilas = clienteMapper.countByExample(example);
			List<Cliente> clientes = clienteMapper.selectByExample(example, new RowBounds((pagina-1)*filas, filas));
			mav.addObject("pagina", pagina);
			mav.addObject("totalpaginas", (int)Math.ceil(((double)totalfilas/(double)filas)));
			mav.addObject("totalfilas", totalfilas);
			mav.addObject("datos", clientes);
			return mav;
		}
	}
	
}
